package grape.workflow.rest.processinstance.mvc;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.fasterxml.jackson.databind.node.ObjectNode;
import grape.common.exception.ExceptionTools;
import grape.common.rest.form.BasePageForm;
import grape.workflow.rest.common.mvc.BaseController;
import grape.workflow.rest.processinstance.form.ProcessInstanceListPageForm;
import grape.workflow.rest.processinstance.mapper.ProcessInstanceWebMapper;
import grape.workflow.rest.processinstance.vo.ProcessInstanceRepresentationVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.flowable.ui.common.model.ResultListDataRepresentation;
import org.flowable.ui.task.model.runtime.ProcessInstanceRepresentation;
import org.flowable.ui.task.service.runtime.FlowableProcessInstanceQueryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;
import springfox.documentation.annotations.ApiIgnore;

import java.util.List;
import java.util.stream.Collectors;

/**
 * Created by yangwei
 * Created at 2020/6/23 14:34
 */
@RestController
@RequestMapping("/workflow/instance")
@Api(tags = "流程实例相关接口")
public class ProcessInstanceController extends BaseController {



    @Autowired
    protected FlowableProcessInstanceQueryService processInstanceQueryService;
    @Autowired
    private ProcessInstanceWebMapper processInstanceWebMapper;


    /**
     * 我发起的流程
     * @param form
     * @return
     */
    @ApiOperation("我发起的流程")
    @PreAuthorize("hasAuthority('process:instances:startedByMe:listPage')")
    @GetMapping(value = "/instances/startedByMe/listPage")
    @ResponseStatus(HttpStatus.OK)
    public IPage<ProcessInstanceRepresentationVo> taskToDoPageList(ProcessInstanceListPageForm form, @ApiIgnore String loginUserId) {
        ObjectNode jsonNode = handleRequestParam(form);
        jsonNode.put("startedBy", loginUserId);

        // 查询任务列表
        ResultListDataRepresentation resultListDataRepresentation = processInstanceQueryService.getProcessInstances(jsonNode);
        return handleResult(resultListDataRepresentation, form);
    }

    private IPage<ProcessInstanceRepresentationVo> handleResult(ResultListDataRepresentation resultListDataRepresentation, BasePageForm pageForm) {
        // 组装分页数据

        IPage objectPage = newPage(resultListDataRepresentation, pageForm);
        List<ProcessInstanceRepresentation> result = (List<ProcessInstanceRepresentation>) resultListDataRepresentation.getData();
        if (isEmpty(result)) {
            throw ExceptionTools.dataNotExistRE("数据不存在");
        }

        // 转vo,添加时间
        List<ProcessInstanceRepresentationVo> r = handleVo(result);


        objectPage.setRecords(r);
        return objectPage;
    }
    private ObjectNode handleRequestParam(ProcessInstanceListPageForm form) {
        ObjectNode jsonNode = newObjectNode();
        // 以下魔法变量参见 org.flowable.ui.task.service.runtime.FlowableProcessInstanceQueryService.getProcessInstances
        handlePage(form, jsonNode);
        jsonNode.put("businessKey", form.getBusinessKey());
        if (form.getIsRunning() != null) {
            jsonNode.put("state", form.getIsRunning()? "running": "completed");
        }
        return jsonNode;
    }
    private List<ProcessInstanceRepresentationVo> handleVo(List<ProcessInstanceRepresentation> result){
        return result.stream().map(item -> {
            ProcessInstanceRepresentationVo vo = processInstanceWebMapper.map(item);
            return vo;
        }).collect(Collectors.toList());
    }

}
